<?php

namespace App\Jobs;

use App\Model\BotsModel;
use App\Service\BotsService;
use App\Service\DologinService;
use Exception;

class LoginRobotJob extends Job
{
	protected $botId = 0;

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($botId)
	{
		$this->botId = $botId;
	}

	/**
	 * 获取机器人信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	protected function getBotsInfoBybotId($botId)
	{
		return BotsModel::getBotsInfoBybotId($botId);
	}

	protected function loginRobot()
	{
		try {
			$bots = $this->getBotsInfoBybotId($this->botId);
			if (!$bots) {
				throw new Exception('query bots failed, botid:'.$this->botId."\r\n");
			}

			if ((time() - strtotime($bots['last_login_time'])) < 600) {
				throw new Exception('The robot has a short time log, botid:'.$this->botId."\r\n");
			}

			$setting = BotsService::getInstance()->getBotsSetting($bots);
			// login robot
			$res = DologinService::getInstance()->dologin($setting);
			if (!$res) {
				dispatch((new LoginRobotJob($this->botId))->onQueue($this->job->getQueue())->delay(1));
				// robot landing queue
				throw new Exception('login robot failed, botid:'.$this->botId."\r\n");
			}

			$this->job->delete();
			echo 'login robot success, botid:'.$this->botId."\r\n";
			return true;
		} catch (Exception $e) {
			echo $e->getMessage();
			$this->job->delete();
			return false;
		}
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		$this->loginRobot();
		echo '数据查询完毕!'."\r\n";
		return true;
	}
}
